package com.sgcc.nfc.lock.data.remote.dto.auth

import com.google.gson.annotations.SerializedName
import com.sgcc.nfc.lock.core.storage.AuthToken
import com.sgcc.nfc.lock.domain.model.LoginResult
import com.sgcc.nfc.lock.domain.model.UserProfile

data class LoginResponseDto(
    @SerializedName("accessToken") val accessToken: String?,
    @SerializedName("token") val legacyToken: String?,
    @SerializedName("refreshToken") val refreshToken: String?,
    @SerializedName("tokenType") val tokenType: String?,
    @SerializedName("expiresIn") val expiresIn: Long?,
    @SerializedName("userInfo") val userInfo: UserDto?
) {
    fun toDomain(): LoginResult? {
        val tokenValue = accessToken ?: legacyToken ?: return null
        val profile = userInfo?.toDomain() ?: return null
        val expiresAt = expiresIn?.takeIf { it > 0 }?.let { seconds ->
            System.currentTimeMillis() + seconds * 1000
        }
        return LoginResult(
            token = AuthToken(
                accessToken = tokenValue,
                refreshToken = refreshToken.orEmpty(),
                tokenType = tokenType ?: "Bearer",
                expiresAt = expiresAt
            ),
            profile = profile
        )
    }
}

data class UserDto(
    @SerializedName("userId") val userId: Long?,
    @SerializedName("username") val username: String?,
    @SerializedName("realName") val realName: String?,
    @SerializedName("phone") val phone: String?,
    @SerializedName("roleType") val roleType: Int?,
    @SerializedName("roleName") val roleName: String?,
    @SerializedName("regionId") val regionId: Long?,
    @SerializedName("regionName") val regionName: String?
) {
    fun toDomain(): UserProfile = UserProfile(
        userId = userId ?: 0L,
        username = username.orEmpty(),
        realName = realName.orEmpty(),
        phone = phone,
        roleType = roleType ?: 0,
        roleName = roleName,
        regionId = regionId,
        regionName = regionName
    )
}
